var util = require('../../utils/util.js');
var api = require('../../config/api.js');
var check = require('../../utils/check.js');
var area = require('../../utils/area.js');

var app = getApp();
//TODO 从后端获取
const origins = {
  '国内': ['云南', '四川', '广东', '东北', '山东'],
  '国外': ['加拿大', '美国', '朝鲜', '俄罗斯', '日本'],
  '其他': ['较广', '其他', '投料', '人工', '进口'],
};
Page({
  data: {
    shopInfo: null,
    herbArray: [],
    herbArrayAll: [],
    openSelectHerb: false,
    billArray: ['发票', '收购手续', '发票或收购手续', '其他'],
    openSelectBill: false,
    originArray: [{
        values: Object.keys(origins),
        className: 'column1',
      },
      {
        values: origins['国内'],
        className: 'column2',
        defaultIndex: 0,
      },
    ],
    openSelectOrigin: false,
    sendSamplesArray: ['不提供样品', '提供样品'],
    openSelectSendSamples: false,
    supply: {
      id: 0,
      shopId: 0,
      userType: 0,
      herbId: '',
      herbCode: '',
      herbName: '',
      herbSpecifications: '',
      quantity: '',
      price: '',
      billIndex: 0,
      billValue: '',
      originIndex: 0,
      originValue: '',
      inventoryPlace: '',
      qualityStandard: '',
      sendSamplesIndex: 0,
      sendSamplesValue: '',
      packingMethod: '',
      payMethod: '',
      dueTime: '',
      contactName: '',
      contactTel: '',
    },
    fileList: [],
    supplyId: 0,
    dueTimeMinDate: new Date().setDate(new Date().getDate() + 1),
  },
  addDate(n) {
    let date = new Date();
    date.setDate(date.getDate() + n);
    return date;
  },
  bindinputHerbSpecifications(event) {
    let supply = this.data.supply;
    supply.herbSpecifications = event.detail.value;
    this.setData({
      supply: supply
    });
  },
  bindinputQuantity(event) {
    let supply = this.data.supply;
    supply.quantity = event.detail.value;
    this.setData({
      supply: supply
    });
  },
  bindinputPrice(event) {
    let supply = this.data.supply;
    supply.price = event.detail.value;
    this.setData({
      supply: supply
    });
  },
  bindinputPayMethod(event) {
    let supply = this.data.supply;
    supply.payMethod = event.detail.value;
    this.setData({
      supply: supply
    });
  },
  bindPickerBillChange(event) {
    let supply = this.data.supply;
    supply.billIndex = event.detail.value;
    this.setData({
      supply: supply
    });
  },
  bindinputQualityStandard(event) {
    let supply = this.data.supply;
    supply.qualityStandard = event.detail.value;
    this.setData({
      supply: supply
    });
  },
  bindinputQualificationRequirements(event) {
    let supply = this.data.supply;
    supply.qualificationRequirements = event.detail.value;
    this.setData({
      supply: supply
    });
  },
  bindinputPackingMethod(event) {
    let supply = this.data.supply;
    supply.packingMethod = event.detail.value;
    this.setData({
      supply: supply
    });
  },
  bindinputInventoryPlace(event) {
    let supply = this.data.supply;
    supply.inventoryPlace = event.detail.value;
    this.setData({
      supply: supply
    });
  },
  bindinputContactName(event) {
    let supply = this.data.supply;
    supply.contactName = event.detail.value;
    this.setData({
      supply: supply
    });
  },
  bindinputContactTel(event) {
    let supply = this.data.supply;
    supply.contactTel = event.detail.value;
    this.setData({
      supply: supply
    });
  },
  //药材选择处理
  getHerbItemList() {
    let that = this;
    util.request(api.HerbSelectList).then(function (res) {
      if (res.errno === 0) {
        // console.log(res.data.list)
        that.setData({
          herbArray: res.data.list,
          herbArrayAll: res.data.list,
        });
      }
    });
  },
  herbShow() {
    this.setData({
      openSelectHerb: true
    });
  },
  onHerbPopUpSearchChange(e) {
    let that = this;
    let selectHerbSearch = e.detail;
    let herbArray = that.data.herbArrayAll.filter((t) => (
      that.findValue(t.code, selectHerbSearch) || that.findValue(t.name, selectHerbSearch) || that.findValue(t.specifications, selectHerbSearch)
    ));
    that.setData({
      herbArray: herbArray || []
    });
  },
  findValue(str, value) {
    if (str != null && value != null && str.indexOf(value) > -1) {
      return true;
    }
    return false;
  },
  onHerbClose() {
    this.setData({
      openSelectHerb: false
    });
  },
  onHerbConfirm(event) {
    let supply = this.data.supply;
    supply.herbId = event.detail.value.id;
    supply.herbCode = event.detail.value.code;
    supply.herbSpecifications = event.detail.value.specifications;
    supply.herbName = event.detail.value.name;
    this.setData({
      supply: supply,
      openSelectHerb: false
    });
  },
  //票价需求处理
  billShow() {
    this.setData({
      openSelectBill: true
    });
  },
  onBillClose() {
    this.setData({
      openSelectBill: false
    });
  },
  onBillConfirm(event) {
    let supply = this.data.supply;
    supply.billIndex = event.detail.index;
    supply.billValue = event.detail.value;
    this.setData({
      supply: supply,
      openSelectBill: false
    });
  },
  //产地处理
  originShow() {
    this.setData({
      openSelectOrigin: true
    });
  },
  onOriginChange(event) {
    const {
      picker,
      value,
      index
    } = event.detail;
    picker.setColumnValues(1, origins[value[0]]);
  },
  onOriginClose() {
    this.setData({
      openSelectOrigin: false
    });
  },
  onOriginConfirm(event) {
    let supply = this.data.supply;
    supply.originIndex = event.detail.index;
    supply.originValue = event.detail.value.join(',');
    this.setData({
      supply: supply,
      openSelectOrigin: false
    });
  },
  //是否寄样
  sendSamplesShow() {
    this.setData({
      openSelectSendSamples: true
    });
  },
  onSendSamplesClose() {
    this.setData({
      openSelectSendSamples: false
    });
  },
  onSendSamplesConfirm(event) {
    let supply = this.data.supply;
    supply.sendSamplesIndex = event.detail.index;
    supply.sendSamplesValue = event.detail.value;
    this.setData({
      supply: supply,
      openSelectSendSamples: false
    });
  },
  //结束日期
  bindinputDuteTime(event) {
    let supply = this.data.supply;
    supply.dueTime = event.detail.value;
    this.setData({
      supply: supply
    });
  },
  dueTimeShow() {
    this.setData({
      openSelectDueTime: true
    });
  },
  onDueTimeClose() {
    this.setData({
      openSelectDueTime: false
    });
  },
  onDueTimeConfirm(event) {
    let supply = this.data.supply;
    supply.dueTime = this.formatDate(event.detail);
    this.setData({
      supply: supply,
      openSelectDueTime: false
    });
  },
  formatDate(date) {
    date = new Date(date);
    return `${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()}`;
  },

  getSupplyDetail() {
    let that = this;
    util.request(api.SupplyDetail, {
      id: that.data.supplyId
    }).then(function (res) {
      if (res.errno === 0) {
        if (res.data) {
          that.setData({
            supply: res.data
          });
        }
      }
    });
  },
  setShopInfo() {
    let shopInfo = this.data.shopInfo;
    if (shopInfo && shopInfo.id && (shopInfo.userType == '0' || shopInfo.userType == '1')) {
      let supply = this.data.supply;
      supply.shopId = shopInfo.id;
      supply.userType = shopInfo.userType;
      // console.log(supply)
      if (shopInfo.contactName) {
        supply.contactName = shopInfo.contactName;
      }
      if (shopInfo.contactTel) {
        supply.contactTel = shopInfo.contactTel;
      }
      this.setData({
        supply: supply
      });
    }
  },
  afterRead(event) {
    const {
      file
    } = event.detail;
    this.upload(file);
  },
  upload: function (file) {
    var that = this;
    const uploadTask = wx.uploadFile({
      url: api.StorageUpload,
      filePath: file.url,
      name: 'file',
      success: function (res) {
        console.log(res)
        var _res = JSON.parse(res.data);
        if (_res.errno === 0) {
          // 上传完成需要更新 fileList
          var url = _res.data.url
          const {
            fileList = []
          } = that.data;
          fileList.push({
            ...file,
            url: url
          });
          that.setData({
            fileList
          });
        }
      },
      fail: function (e) {
        wx.showModal({
          title: '错误',
          content: '上传失败',
          showCancel: false
        })
      },
    })

    uploadTask.onProgressUpdate((res) => {
      console.log('上传进度', res.progress)
      console.log('已经上传的数据长度', res.totalBytesSent)
      console.log('预期需要上传的数据总长度', res.totalBytesExpectedToSend)
    })

  },
  onLoad: function (options) {
    // 页面初始化 options为页面跳转所带来的参数
    console.log(options)
    if (options.id && options.id != 0) {
      this.setData({
        supplyId: options.id
      });
      this.getSupplyDetail();
    }
  },
  onReady: function () {

  },
  cancelSupply() {
    wx.navigateBack();
  },
  saveSupply() {
    console.log(this.data.supply)
    let supply = this.data.supply;

    if (supply.herbName == '') {
      util.showErrorToast('请选择药材');

      return false;
    }

    if (supply.quantity == '') {
      util.showErrorToast('请输入供应数量');
      return false;
    }

    // if (supply.billValue == '') {
    //   util.showErrorToast('请选择票据需求');
    //   return false;
    // }

    if (supply.originValue == '') {
      util.showErrorToast('请输入产地');
      return false;
    }

    if (supply.inventoryPlace == '') {
      util.showErrorToast('请输入库存地');
      return false;
    }

    if (supply.qualityStandard == '') {
      util.showErrorToast('请输入质量标准');
      return false;
    }

    if (supply.sendSamplesValue == '') {
      util.showErrorToast('请选择是否寄样');
      return false;
    }

    // if (supply.packingMethod == '') {
    //   util.showErrorToast('请输入包装方式');
    //   return false;
    // }

    if (supply.dueTime == '') {
      util.showErrorToast('请选择结束日期');
      return false;
    }

    if (supply.contactName == '') {
      util.showErrorToast('请输入联系人');
      return false;
    }

    if (supply.contactTel == '') {
      util.showErrorToast('请输入联系电话');
      return false;
    }

    if (this.data.fileList.length == 0) {
      util.showErrorToast('请上传图片');
      return false;
    }

    let herbListImage = '';
    if (this.data.fileList) {
      herbListImage = this.data.fileList.map((t) => t.url).join(',')
    }
    let that = this;
    util.request(api.SupplySave, {
      id: supply.id,
      shopId: supply.shopId,
      userType: supply.userType,
      herbId: supply.herbId,
      herbCode: supply.herbCode,
      herbName: supply.herbName,
      herbSpecifications: supply.herbSpecifications,
      quantity: supply.quantity,
      price: supply.price,
      payMethod: supply.payMethod,
      billDemand: supply.billValue,
      herbOrigin: supply.originValue,
      inventoryPlace: supply.inventoryPlace,
      qualityStandard: supply.qualityStandard,
      qualificationRequirements: supply.qualificationRequirements,
      sendSamples: supply.sendSamplesValue,
      packingMethod: supply.packingMethod,
      dueTime: util.formatTime2(new Date(supply.dueTime), "Y-M-D h:m:s"),
      contactName: supply.contactName,
      contactTel: supply.contactTel,
      herbListImage: herbListImage
    }, 'POST').then(function (res) {
      if (res.errno === 0) {
        //返回之前，先取出上一页对象，并设置supplyId
        var pages = getCurrentPages();
        var prevPage = pages[pages.length - 2];
        console.log(prevPage);
        if (prevPage.route == "pages/checkout/checkout") {
          prevPage.setData({
            supplyId: res.data
          })

          try {
            wx.setStorageSync('supplyId', res.data);
          } catch (e) {

          }
          console.log("set supply");
        }
        wx.navigateBack();
      }
    });

  },
  onShow: function () {
    this.getHerbItemList();
    // 页面显示
    if (app.globalData.hasLogin) {
      let shopInfo = wx.getStorageSync('shopInfo');
      this.setData({
        shopInfo: shopInfo
      });
      this.setShopInfo();
    } else {
      // wx.navigateTo({
      //   url: "/pages/auth/login/login"
      // });
    };
  },
  onHide: function () {
    // 页面隐藏

  },
  onUnload: function () {
    // 页面关闭

  }
})